package search;

import java.util.ArrayList;

public class BinarySearch {
    private static ArrayList<Integer> list = new ArrayList<>();

    public static void main(String[] args) {
        int arr[] = {12, 32, 83, 84, 84, 91, 100, 123, 321};
        System.out.println(search(arr, 0, 8, 84));
        search2(arr, 0, 8, 84);
        System.out.println(list);
    }

    // 返回下标, 闭区间
    private static int search(int arr[], int left, int right, int findVal) {
        // 找不到返回 -1
        if (left > right) {
            return -1;
        }

        int mid = (left + right) / 2;

        // 左
        if (findVal < arr[mid]) { //
            return search(arr, left, mid - 1, findVal);
        } else if (findVal > arr[mid]) { //右
            return search(arr, mid + 1, right, findVal);
        } else {
            return mid;
        }
    }

    // 返回下标数组, 闭区间
    private static void search2(int arr[], int left, int right, int findVal) {
        int mid = (left + right) / 2;

        if (left > right) {
            return;
        }
        // 左
        if (findVal < arr[mid]) { //
            search2(arr, left, mid - 1, findVal);
        } else if (findVal > arr[mid]) { //右
            search2(arr, left, mid - 1, findVal);
        } else { //
            list.add(mid);
            // 左边看看
            int temp = mid - 1;
            while (temp >= 0 && arr[temp] == findVal) {
                list.add(temp--);
            }
            // 右边看看
            temp = mid + 1;
            while (temp < arr.length && arr[temp] == findVal) {
                list.add(temp++);
            }
        }
    }
}
